<script lang="ts" setup>
import API from "@/service/api/order";
import { request } from "@/service/request";
import { useRoute } from 'vue-router';
import { reactive, ref } from "vue";
import { mStyles } from "@/utils/useStyles";
import waitFurther from "./plugin/index.vue";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { useClipboard } from '@vueuse/core'
import { useFullPage } from "@/hook/useFullPage";
import { someFieldStore } from "@/stores/somefield";
import { truncateText } from "@/utils/ellipsis";

// 定义订单记录接口类型
interface OrderRecord {
    order_num: string;
    user_name: string;
    work_order_template_name: string;
    uid: string;
    game_name: string;
    server_name: string;
    role_name: string;
    order_status: string;
    is_appraise: number;
    handle_status: string;
}

//定义订单日志接口类型
interface OrderLogs {
    // 根据实际API响应定义属性
    [key: string]: any;
}

// 新增：定义API响应接口
interface OrderDetailResponse {
    order_logs: OrderLogs;
    order_record: OrderRecord;
    further_parts?: any; // 添加可选属性
}

const mRoute = useRoute();

const mTitleMap = {
    applyOrder: '你的工单已提交',
    userUrgent: '你催促处理中',
    restart: '你重新提交了工单',
    finish: '客服处理完成',
    message: '客服留言',
    furtherNotice: '客服留言',
    finishFurther: '你提交了材料',
    close: '系统'
} as const;

// 获取当前标题的函数
function clkCurrentTitle(player_link_type: keyof typeof mTitleMap) {
    return mTitleMap[player_link_type] || '';
}

// 判断是否应该隐藏内容
function clkShouldHideContent(type: keyof typeof mTitleMap): boolean {
    return type === 'finish' || type === 'userUrgent';
}

function clkShouldHideTitle(type: keyof typeof mTitleMap): boolean {
    return type === 'finish' || type === 'userUrgent';
}

function clkShouldHidePartname(type: keyof typeof mTitleMap): boolean {
    return type === 'furtherNotice';
}

// 修改：为mOrderDetail添加类型约束
const mOrderDetail = reactive<{
    order_logs: OrderLogs;
    order_record: OrderRecord | null;
}>({
    order_logs: {},
    order_record: null,
});

//是否添自定义消息
function clkIsAdd(type: keyof typeof mTitleMap): boolean {
    return type === 'finish';
}

//是否显示为蓝色
function clkIsBlue(type: keyof typeof mTitleMap): boolean {
    return type === 'finish' || type === 'furtherNotice' || type === 'message';
}

//拿到详情
const mSubmit = ref(true);
const mActionText = ref('处理中');


//未登录查看详情
const mSomefield = someFieldStore();
const mApiurl = ref();
const mDetail = ref(true);
if (mSomefield.order_num != "") {
    mApiurl.value = API.orderrecordDetail;
    mDetail.value = false;
} else {
    mApiurl.value = API.orderRecordDetail;
    mDetail.value = true;
}



const clkGetOrderDetail = async () => {
    const { data } = await request.post<OrderDetailResponse>(mApiurl.value, { order_num: mRoute.query.order_num });
    mOrderDetail.order_logs = data.order_logs;
    mOrderDetail.order_record = data.order_record;

    // 根据订单状态设置按钮文本和状态
    switch (mOrderDetail.order_record.order_status) {
        case 'waitFurther':
            await clkGetOrderFurtherPart();
            mSubmit.value = false;
            mFurtherPart.title = data.order_logs[0]?.content?.[0]?.part_value || '';
            mActionText.value = '补充资料';
            break;
        case 'finish':
            mActionText.value = mOrderDetail.order_record.is_appraise === 1 ? '已评价' : '待评价';
            mSubmit.value = mOrderDetail.order_record.is_appraise === 1;
            break;
        case 'close':
            mActionText.value = mOrderDetail.order_record.is_appraise === 1 ? '工单完结' : '待评价';
            mSubmit.value = mOrderDetail.order_record.is_appraise === 1;
            break;
        case 'wait':
            mActionText.value = '处理中';
            mSubmit.value = true;
            break;
        case 'restart':
            if (mOrderDetail.order_record.handle_status == 'wait') {
                mActionText.value = '处理中';
                mSubmit.value = true;
            }
            break;
        default:
            mActionText.value = '处理中';
            mSubmit.value = true;
    }

}
clkGetOrderDetail()

//拿到待补充的资料
const mFurtherPart = reactive({
    further_parts: {} as any,
    title: ''
});
const clkGetOrderFurtherPart = async () => {
    const { data }: any = await request.post(API.getOrderFurtherPart, { order_num: mRoute.query.order_num });
    mFurtherPart.further_parts = data.further_parts;
}

//自定义插入回复的消息
function clkFilteredLogs() {
    const logs = Array.isArray(mOrderDetail.order_logs)
        ? mOrderDetail.order_logs
        : Object.values(mOrderDetail.order_logs);

    // 找到所有需要插入的索引
    const stopIndexes = logs
        .map((item, idx) => clkIsAdd(item.player_link_type) ? idx : -1)
        .filter(idx => idx !== -1)
        .sort((a, b) => b - a);

    let result = [...logs]; // 拷贝，避免影响原数组

    // 循环插入自定义客服消息
    stopIndexes.forEach((stopIndex) => {
        const base = result[stopIndex]; // 插入后索引要加上已插入的数量
        const newDataItem = {
            player_link_type: 'message',
            created_at: base.created_at,
            content: [
                {
                    part_id: 0,
                    part_key: '',
                    part_name: '',
                    part_value: base?.content?.[0]?.part_value || ''
                },
            ],
            pic_content: [
                {
                    part_id: 0,
                    part_key: '',
                    part_name: '',
                    pic_value: base?.pic_content?.[0]?.pic_value || []
                }
            ]
        };
        result.splice(stopIndex, 0, newDataItem);

    });
    return result;
};

const { removeCachedView } = useDynamicKeepAlive()
const clkBeforeClose = () => {
    clkGetOrderDetail()
    mEvaluateRef.value.closeDialog();

    //更改刷新store通知列表页刷新
    removeCachedView('', 'order');
};

const mActive = ref(0);
const clkImagePreview = (url: string) => {
    showImagePreview([url]);
};

const mWaitFurtherRef = ref();

//根据order的状态对应的操作
const mEvaluateRef = ref();
const clkActionType = () => {
    if (!mOrderDetail.order_record) return;

    switch (mOrderDetail.order_record.order_status) {
        case 'waitFurther':
            mWaitFurtherRef.value?.openDialog();
            break;
        case 'finish':
            if (mOrderDetail.order_record.is_appraise === 0) {
                mEvaluateRef.value?.openDialog();
            }
            break;
        case 'close':
            if (mOrderDetail.order_record.is_appraise === 0) {
                mEvaluateRef.value?.openDialog();
            }
        break;
    }
};


//复制单号
const { copy } = useClipboard({ legacy: true })
const clkCopy = () => {
    mOrderDetail.order_record && copy(mOrderDetail.order_record.order_num);
    showToast({ message:'复制成功'});
};

const { pageRef } = useFullPage({
  excludeFixedElements: ['.gr-bottom']
})
</script>

<template>
    <cNavbar :iTitle="truncateText(mOrderDetail.order_record?.work_order_template_name, 10)" :iFontColor="mStyles?.color2" :iBgColor="mStyles?.color10" leftArrow iFixed></cNavbar>
    <div class="bg" ref="pageRef">
    <ul class="gr-list-ul" v-if="mOrderDetail.order_record">
        <li>
            工单号：
            <span>{{ mOrderDetail.order_record.order_num }}</span>
            <span class="color-[#FF0000] m-l-[60px] text-[24px]" @click="clkCopy">复制</span>
        </li>
        <li>工单类型：<span>{{ mOrderDetail.order_record.work_order_template_name }}</span></li>
        <li>账号信息：<span>{{ mOrderDetail.order_record.user_name }}</span></li>
        <li>游戏名称：<span>{{ mOrderDetail.order_record.game_name }}</span></li>
        <li>区服信息：<span>{{ mOrderDetail.order_record.server_name }}</span></li>
        <li>角色信息：<span>{{ mOrderDetail.order_record.role_name }}</span></li>
    </ul>
    <div class="gr-steps pbottom">
        <van-steps :active="mActive" direction="vertical" active-color="#3D3D3D">
            <van-step v-for="(item, index) in clkFilteredLogs()" :key="item['id']">
                <div class="gr-step-header flex justify-between m-b-[10px]">
                    <h1 class="text-3.906vmin font-medium">{{ clkCurrentTitle(item.player_link_type) }}</h1>
                    <span class="color-[#3D3D3D]/40 text-[24px]">{{ item.created_at }}</span>
                </div>
                <div
                    :class="item.player_link_type == 'applyOrder' || item.player_link_type == 'finishFurther' ? 'gr-bg' : ''">
                    <div class="gr-step-content">
                        <ul>
                            <li v-for="(itemcon, ind) in item.content" :key="itemcon['id']"
                                v-show="!clkShouldHideTitle(item.player_link_type)">
                                <span v-show="!clkShouldHidePartname(item.player_link_type)"
                                    class="text-[24px] font-normal">
                                    {{ itemcon.part_name }}
                                    <span v-show="itemcon.part_name != ''">：</span>
                                </span>
                                <span :class="clkIsBlue(item.player_link_type) ? '' : ''"
                                    class="color-[#3D3D3D]/80 font-medium text-[24px] break-words">
                                    {{ itemcon.part_value }}
                                </span>
                            </li>
                        </ul>
                    </div>
                    <div class="gr-step-pic" v-for="(itempic) in item.pic_content"
                        v-show="!clkShouldHideContent(item.player_link_type)">
                        <h1 v-show="!clkShouldHidePartname(item.player_link_type)" class="text-[24px] font-normal">
                            {{ itempic.part_name }}
                            <span v-show="itempic.part_name != ''">：</span>
                        </h1>
                        <div class="gr-pic">
                            <van-image v-for="(ite) in itempic.pic_value" :key="ite.id"
                                :src="`${ite}?x-oss-process=image/resize,p_30`"  fit="contain" width="16vmin" height="16vmin"
                                @click="clkImagePreview(ite)"></van-image>
                        </div>
                    </div>
                </div>
            </van-step>
        </van-steps>
    </div>
    <div class="gr-bottom" v-show="mDetail">
        <cButton iLinearGradien :iColor="mStyles?.color10" class="w-[100%]" @click="clkActionType" :disabled="mSubmit"
            round>
            {{ mActionText }}
        </cButton>
    </div>
    </div>
    <waitFurther ref="mWaitFurtherRef" :orderPart="mFurtherPart" :mFurTitle="mOrderDetail.order_logs" @is-Confirm="clkBeforeClose" v-if="mOrderDetail.order_logs">
    </waitFurther>
    <cEvaluate ref="mEvaluateRef" @is-Confirm="clkBeforeClose" :orderData="mOrderDetail.order_record"
        v-if="mOrderDetail.order_record"></cEvaluate>
</template>

<style lang="scss" scoped>
.bg{
   background:#F6F6F6;
}
.gr-list-ul {
    background: $color10;
    margin: 20px 24px 10px 24px;
    padding: 20px;
    font-size: calc($fontSize + 9px);
    border-radius: 24px;
    color: $color2;

    li {
        color: #3D3D3D;
        font-size: 26px;
        font-weight: 500;
        margin-bottom:10px;
        span {
            font-weight: 400;
        }
    }

    .gr-progress {
        margin-top: 10px;
        background: $color4;
        border-radius: 5px;
        font-size: calc($fontSize + 7px);
        padding: 5px;
    }

    .gr-list-image {
        width: 100%;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(15vmin, 1fr));
        gap: 2.133vmin;
    }
}

.pbottom {
    padding-bottom: 200px;
}

.gr-steps {
    margin: 24px;

    :deep(.van-steps) {
        border-radius: 20px;
        padding: 10px;
    }

    :deep(.van-step) {
        color: rgba(61, 61, 61, 0.6);
    }

    :deep(.van-hairline:after) {
        border: none;
    }

    :deep(.van-step--vertical) {
        padding-left: 35px;
    }

    :deep(.van-step__circle) {
        width: 16px;
        height: 16px;
        background: #E6E6E6;
        border-radius: 50px;
    }

    :deep(.van-step__line) {
        width: 2px;
        left: 14px;
        background: #E6E6E6;
    }

    :deep(.van-step__icon--active) {
        width: 24px;
        height: 24px;
        background: url('/round.png') no-repeat;
        background-size: 100%;
    }

    :deep(.van-step__circle-container) {
        left: 15px;
        margin: 7px 0 7px 0;
        background:white;
    }

    :deep(.van-icon-checked:before) {
        content: none;
    }

    .gr-step-content {
        ul {
            li {
                justify-content: flex-start;
            }
        }
    }

    .gr-step-pic {
        display: flex;
        justify-content: flex-start;

        .gr-pic {
            margin: 0.667vmin;
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(15vmin, 1fr));
            gap: 2.133vmin;
            flex: 1;
            :deep(.van-image__img){
                border-radius:12px;
            }
        }
    }

    .gr-bg {
        border-radius: 5px;
        background: #F6F9FB;
        padding: 5px;
    }
}

.gr-bottom {
    position: fixed;
    bottom: 0px;
    left: 0px;
    background: $color10;
    width: 100%;
    text-align: center;
    padding: 50px;
    z-index: 999;
}
</style>